package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/admin.html","/insertProduct.html","/insertBanner.html"})
public class MyFilter implements Filter {
    //初始化方法
    public void init(FilterConfig config) throws ServletException {
    }
    //销毁方法
    public void destroy() {
    }
    //当客户端请求资源之前和之后执行的方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("过滤器工作了!");
        //将父类类型转成子类类型
        HttpServletRequest rt = (HttpServletRequest) request;
        HttpServletResponse re = (HttpServletResponse) response;
        //获取Session
        HttpSession session = rt.getSession();
        //从Session中获取user
        User user = (User) session.getAttribute("user");
        if (user!=null){//登录了
            //放行
            chain.doFilter(request, response);
        }else{//没登录
            //通知客户端进入登录页面
            re.sendRedirect("/login.html");
        }
    }
}
